package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.dao.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * @version V1.0
 * @author: yongjichu
 * @date: 2020/2/8 17:08
 * @description:
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    /**
     * 根据用户名获取用户的密码，角色还有权限
     * @return
     * @param username
     */
    @Override
    public User findByUsername(String username) {
        /**
         * 根据用户名获取用户的信息
         */
        User user=userMapper.findByUsername(username);
        if(user==null){
            return null;
        }


        Set<Role> roles=roleMapper.findByUserId(user.getId());

        if(CollectionUtil.isNotEmpty(roles)){
            for (Role role : roles) {
                // * 根据role的id获取对应的权限，然后将得到的权限设置到role对象中，因为role对象中有private Set<Permission> permissions = new HashSet<Permission>(0);
                Set<Permission> permissions=permissionMapper.findByRoleId(role.getId());
                role.setPermissions(permissions);
            }
            user.setRoles(roles);
        }
      /*  User user1=userMapper.findByUserId(user.getId());*/

        return user;
    }
}
